package nthu.web.view;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nthu.web.listener.LoginSessionListener;
import nthu.web.model.domain.User;
import java.sql.*;



@SuppressWarnings("serial")
public class UserLoginView extends ResourceView<User> {


	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
                                          throws ServletException, IOException {

		response.setContentType("text/html;charset=utf8");
       
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();

		out.println("<html>");
        out.println("<head>");
        out.println("<title>Login Page</title>");
        out.println("</head>");
        out.println("<body>");
        
        if(session.getAttribute("username")==null){

        	out.println("<form name=\"userlogin\" action=\"login\" method=\"post\">");
        	out.println("Username <input type=\"text\" name=\"username\" value=\"\" ><br/>");
        	out.println("Password <input type=\"password\" name=\"password\" value=\"\"  ><br/>");
        	out.println("<input type=\"submit\" value=\"Login\">");
        	out.println("</form>");
        	out.println("<a href=\"./\">回首頁</a>！");

        }else{

        	out.println(session.getAttribute("username")+"   你已經登入成功！<br/>");
        	out.println("<a href=\"./\">回首頁</a>！");
        }

        out.println("</body>");
        out.println("</html>");

	}


	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	                                             throws ServletException, IOException {

		HttpSession session = request.getSession();

		String username = request.getParameter("username");
		String password = request.getParameter("password");

		if(username == null || password == null)
			response.sendRedirect("./login");

		String strCheckLogin = checklogin(username,password);

		if(strCheckLogin.equals("success")){
			session.setAttribute("username",username);
			session.setAttribute("password",password);
			// LoginSessionListener.putMap( username, username); 
			// record session information
			response.sendRedirect("./");
		}else{
			response.sendRedirect("./login");
		}
	}


	String checklogin(String LoginUsername,String LoginPassword) throws IOException {
	
		String databaseIP = "localhost";
		String userName = "essweb";
		String userPassword = "essess";
		String targetDataBase ="pipezon";
		String jdbcURL = "jdbc:mysql://" + databaseIP  + "/" + targetDataBase + "?useUnicode=true&amp;characterEncoding=UTF-8";
		String result = null;

		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection(jdbcURL, userName, userPassword);
			Statement stmt = conn.createStatement();

			ResultSet rs = stmt.executeQuery("SELECT * FROM user WHERE username = '"+LoginUsername+"'");

			if(!rs.next()){
				result = "無此帳號";
			}
			else if(!rs.getString("password").equals(LoginPassword)){   //資料庫欄位名稱password
				result = "密碼錯誤";
			}
			else if(rs.getString("password").equals(LoginPassword)){
				result = "success";
			}

			rs.close();
			stmt.close();
			conn.close();
		} catch (ClassNotFoundException ex) {
			System.out.println("找不到驅動程式類別\n");
		} catch (SQLException ex) {
			System.out.print("SQL Exception : " + ex +"\n");
		}

		return result;
	}
	
	

}

